<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="120px"
             status-icon>

      <el-tabs v-model="activeName">
        <el-tab-pane label="基础信息" name="BaseInfo">
          <el-form-item label="名称：" prop="name">
            <el-input v-model="formData.name" :readonly="readonly" maxlength="64" placeholder="请输入名称" show-word-limit/>
          </el-form-item>

          <el-form-item label="级别：" prop="level">
            <el-input-number v-model="formData.level" :disabled="readonly" :min="0" :step="1" controls-position="right" placeholder="请输入级别"/>
          </el-form-item>

          <el-form-item label="级别图标：" prop="icon">
            <el-input v-model="formData.icon" :autosize="{ minRows: 1}" :disabled="readonly" placeholder="请点击上传图标" style="margin-bottom: 5px" type="textarea"/>
            <UploadImage v-model="formData.icon" :disabled="readonly" :show-delete="true"/>
          </el-form-item>

          <el-form-item label="背景图片：" prop="background">
            <el-input v-model="formData.background" :autosize="{ minRows: 1}" :disabled="readonly" placeholder="请点击上传背景图片" style="margin-bottom: 5px" type="textarea"/>
            <UploadImage v-model="formData.background" :disabled="readonly" :show-delete="true"/>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="升级条件" name="UpgradeConfig">
          <el-form-item label="直推粉丝数量：" prop="directly_count">
            <el-input-number v-model="formData.directly_count" :disabled="readonly" :min="0" :step="1" controls-position="right" placeholder="请输入直推粉丝数量"/>
            <span class="tip">直推创客/合伙人数量要求</span>
          </el-form-item>

          <el-form-item label="升级奖励金额：" prop="reward">
            <el-input-number v-model="formData.reward" :disabled="readonly" :min="0" :precision="2" :step="1" controls-position="right" placeholder="请输入级别奖励"/>
            <span class="tip">升级到该级别时奖励的额外奖励</span>
          </el-form-item>

          <template v-if="false">
            <el-divider border-style="dashed"/>

            <el-form-item label="让利分润比例：" prop="bonus_ratio">
              <el-input-number v-model="formData.bonus_ratio" :disabled="readonly" :min="0" :precision="2" :step="0.01" controls-position="right" placeholder="请输入分润比例"/>
              <span class="tip">{{ toPercent(formData.bonus_ratio || 0.00) }} 商家让利部分分润占比</span>
            </el-form-item>

            <el-form-item label="提现分润比例：" prop="bonus_ratio_withdraw">
              <el-input-number v-model="formData.bonus_ratio_withdraw" :disabled="readonly" :min="0" :precision="2" :step="0.01" controls-position="right" placeholder="请输入分润比例"/>
              <span class="tip">{{ toPercent(formData.bonus_ratio_withdraw || 0.00) }} 团队内用户提现手续费分润占比</span>
            </el-form-item>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['config:vip_level:create', 'config:vip_level:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { VipLevelConfig, vipLevelConfigInfo, vipLevelConfigSaveOrUpdate } from '@/api/api-config.ts';
import { UploadImage } from '@/components/upload';
import { toPercent } from '@/utils';

defineOptions({name: 'vip-level-config-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

/** 默认表单数据 */
const defaultForm: VipLevelConfig = <VipLevelConfig>{id: 0, reward: 0, bonus_ratio: 0, bonus_ratio_withdraw: 0};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  level: [{required: true, message: '级别不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

const activeName = ref();
/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '会员级别配置';
  dialogVisible.value = true;
  activeName.value = 'BaseInfo'
  // 重置表单
  handleFormReset();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await vipLevelConfigInfo(id)
      formData.value = data;
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    vipLevelConfigSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select,
  .el-input-number {
    max-width: 13rem;
  }
}
</style>
